package de.kraenksoft.android.cinemaExample;

import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import de.kraenksoft.android.cinemaExample.model.Theater;
import de.kraenksoft.android.cinemaExample.model.WebTheaterFactory;
import de.kraenksoft.android.cinemaExample.presenters.MovieListPresenter;
import de.kraenksoft.android.cinemaExample.presenters.MovieListPresenterImpl;

public class UFProgramApplication extends Application {
	private static UFProgramApplication instance = null;
	
	private MovieListPresenter movieListPresenter = new MovieListPresenterImpl();
	private Theater theater = null;

	protected Exception loadTheaterException = null;
	
	private void loadTheater() throws IOException, ParseException {
		NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
		if (info != null && info.isConnectedOrConnecting()) {
			theater = WebTheaterFactory.createTheater();
		}else{
			throw new IOException("Keine Internetverbindung");
		}
	}
	private Theater getTheater() {
		return theater;
	}

	public MovieListPresenter getMovieListPresenter() {
		return movieListPresenter;
	}

	public static UFProgramApplication getInstance() {
		return instance;
	}

	@SuppressWarnings("static-access")
	public UFProgramApplication() {
		super();
		this.instance = this;
		loadTheaterAsThread();
	}
	
	public void refreshTheater(){
		this.theater = null;
		this.loadTheaterException = null;
		movieListPresenter.setModel(null);
		loadTheaterAsThread();
	}
	
	private void loadTheaterAsThread() {
		Thread thread = new Thread(new Runnable(){

			@Override
			public void run() {
				try {
					loadTheater();
				} catch (IOException e) {
					loadTheaterException = e;
				} catch (ParseException e) {
					loadTheaterException = e;
				}
				handler.sendEmptyMessage(0);
			}
			
		});
        thread.start();
	}
	
	private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	if(loadTheaterException != null) {
        		movieListPresenter.setException(loadTheaterException);
        	}else{
        		movieListPresenter.setModel(getTheater());
        	}
        }
};

	public Calendar getCalToday() {
		return GregorianCalendar.getInstance();
	}
	
	@SuppressWarnings("static-access")
	@Override
	public void onCreate() {
		super.onCreate();
		this.instance = this;
	}
	
	
}
